package kmp;

public class leetCode32_longestValidParentheses {
    //dp[i] 表示长度为i时，最长有效括号长度为dp[i]
    public int longestValidParentheses(String s) {
        if (s == null || s.length() == 0) return 0;
        int length = s.length();
        int[] dp = new int[length];
        char[] chars = s.toCharArray();
        int max = 0;
        for (int i = 1; i < chars.length; i++) {
            if (chars[i] == ')') {
                if (chars[i - 1] == '(') {
                    if (i > 2) {
                        dp[i] = dp[i - 1] + 2;
                    } else {
                        dp[i] = 2;
                    }
                }
                if (i - dp[i - 1] > 0 && chars[i - dp[i - 1] - 1] == '(') {
                    if (i - dp[i - 1] >= 2) {
                        dp[i] = dp[i - 1] + dp[i - dp[i - 1] - 2] + 2;
                    } else {
                        dp[i] = dp[i - 1] + 2;
                    }
                }

                max = Math.max(max, dp[i]);
            }
        }
        return max;
    }
}
